﻿using AiMoBridge.Interface;
using AiMoBridge.Interface.Client;
using AiMoWindows.Entrance;
using AiMoWindows.Localization;
using AiMoWindows.Server;
using AiMoWindows.Windows.Download;

namespace AiMoWindows.MainActions.SecondaryActions
{
    class ScriptDownloader
    {
        readonly IDebugPrinter printer;
        readonly AiMoProgram owner;
        public ScriptDownloader(IDebugPrinter printer, AiMoProgram owner)
        {
            this.owner = owner;
            this.printer = printer;
        }
        public ScriptDownloadResult Result { get; private set; } = new ScriptDownloadResult();

        public async Task<ScriptDownloadResult> DownloadScriptFromShareCode()
        {
            if (!ServerHelper.LogInAsCommunityUser)
            {
                printer.PrintDebug(Local.Get("Only login users can download codes"));
                return Result;
            }
            InputShareKeyWindow inputShareKeyWindow = new InputShareKeyWindow();
            if (inputShareKeyWindow.ShowDialog() != true)
            {
                printer.PrintDebug(Local.Get("Cancel"));
                return Result;
            }

            Result.ShareKey = inputShareKeyWindow.ShareKey;
            printer.PrintDebug(Local.Get("Start download code from: ") + Result.ShareKey);
            string error = "";
            await Task.Run(
                () =>
                {
                    bool re = PerformDownload(Result.ShareKey, out error, out byte[] bytes);
                    Result.Result = re;
                    Result.Bytes = bytes;
                });
            if (Result.Result)
            {
                printer.PrintDebug(Local.Get("Downloaded code from: ") + Result.ShareKey);
            }
            else
            {
                printer.PrintDebug(Local.Get("Download Error: ") + error);
            }
            return Result;
        }
        bool PerformDownload(string shareKey, out string printError, out byte[] bytes)
        {
            try
            {
                IDownloadShareCodeClient client = GetClient.GetDownloadShareCodeClient();
                client.UpdateEvent += owner.Update;
                bool re = client.DownloadBytes(shareKey, out bytes, out printError);
                return re;
            }
            catch (Exception e)
            {
                printError = e.Message;
                bytes = Array.Empty<byte>();
                return false;
            }
        }
    }
}
